﻿using System;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Media;
using Microsoft.Win32;
using Trackr.Core;
using Trackr.GUI.Extensions;
using Application = System.Windows.Application;
using Color = System.Windows.Media.Color;
using ColorConverter = System.Windows.Media.ColorConverter;
using Timer = System.Timers.Timer;

namespace Trackr.GUI.Views
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private const string IdleTimeTask = "Idle time";
        //private System.Timers.Timer _timer;
        public MainWindow()
        {
            //start with windows
            bool autoStart = ConfigUtility.Instance["autostart"].ParseDefault(false);
            RegistryUtility.AutoStart(autoStart, Assembly.GetExecutingAssembly().Location);

            InitializeComponent();
            InitializeTrayIcon();
            InitializeTimer();
            InitializeDragEvents();
        }

        private void InitializeTrayIcon()
        {
            MenuItem hideMenuItem = CreateMenuItem("Hide", () => { this.FadeOut(); });
            MenuItem openMenuItem = CreateMenuItem("Open", () => { this.FadeIn(); });
            MenuItem exitMenuItem = CreateMenuItem("Exit", () => { Close(); });
            var notifyIcon = new NotifyIcon();
            using (
                Stream iconStream =
                    Application.GetResourceStream(
                        new Uri("pack://application:,,,/Trackr.GUI;component/Views/Images/time.ico")).Stream)
            {
                notifyIcon.Icon = new Icon(iconStream);
            }
            notifyIcon.ContextMenu = new ContextMenu(new[] {hideMenuItem, openMenuItem, exitMenuItem});
            notifyIcon.Visible = true;
            notifyIcon.DoubleClick += (sender, e) => { this.FadeIn(); };
        }

        private MenuItem CreateMenuItem(string name, Action clickDelegate)
        {
            return new MenuItem(name, (o, e) => { clickDelegate(); });
        }

        private void InitializeDragEvents()
        {
            gridHeader.MouseLeftButtonDown += (obj, e) => { DragMove(); };
            imageClose.MouseLeftButtonDown += (sender, e) => { this.FadeOut(); };
        }

        private void InitializeTimer()
        {
            //get our datacontext for the main window
            var ctxt = DataContext as MainWindowViewModel;
            if (ctxt == null)
                return;

            //get interval and timeout values from config appData
            int intervalMinutes = ConfigUtility.Instance["interval"].ParseDefault(30);
            int timeOutMinutes = ConfigUtility.Instance["timeout"].ParseDefault(2);

            //setup timers
            var timer = new Timer(TimeSpan.FromMinutes(intervalMinutes).TotalMilliseconds);
            var timeOut = new Timer(TimeSpan.FromMinutes(timeOutMinutes).TotalMilliseconds);

            Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);
            
            //when the timeout timer has elapsed the user has not entered any info so we need to stop the the current timeitem
            timeOut.Elapsed += (sender, e) =>
                {
                    ctxt.StopCurrent();
                    this.Invoke(() =>
                        {
                            //change the color to notify that something happend
                            BorderMain.Background = new LinearGradientBrush(Colors.OrangeRed, Colors.DarkOrange, 90.0);
                            inputTask.Focus();
                        });
                };

            //when the timer has elapsed show the form and start the timeout timer
            timer.Elapsed += (obj, e) =>
                {
                    this.FadeIn();
                    timer.Stop();
                    timeOut.Start();
                };

            //when a task has been submitted start the timer, stop the timeout and hide the window
            ctxt.TaskSubmitted += (timeItem, e) =>
                {
                    this.FadeOut();
                    timer.Start();
                    timeOut.Stop();
                    this.Invoke(
                        () =>
                            {
                                BorderMain.Background =
                                    new SolidColorBrush((Color) ColorConverter.ConvertFromString("#FF4B95D8"));
                            });
                };
        }

        void SystemEvents_SessionSwitch(object sender, Microsoft.Win32.SessionSwitchEventArgs e)
        {
            var viewModel = DataContext as MainWindowViewModel;
            if (viewModel == null)
                return;
            
            switch (e.Reason)
            {
                case SessionSwitchReason.SessionLock:
                    viewModel.CreateNewTask(IdleTimeTask);
                    break;
                case SessionSwitchReason.SessionUnlock:
                    {
                        if(viewModel.PreviousTimeItem != null || viewModel.CurrentTimeItem.Task  != IdleTimeTask )
                        inputTask.Text = viewModel.PreviousTimeItem.Task;
                    }
                    break;
            }
        }
    }
}